// 店铺Datatable
var shopTable;
// 店铺仓库Datatable
var shopWarehouseTable;
// 修改仓库时所选中列的数据
var storChooseData = {
    "isDefault": ""
};
// 正在操作的“店铺ID”
var opShopId = "";
var wizard = $('#rootwizard-custom-circle');

/**
 * 页面初始化
 */
$(function () {

    // 开始时间大于当前时间校验
    $.validator.addMethod("greaterThenNow", function (value, element) {
        if (value) {
            var beginTime = value;
            var endTime = new Date(); // 现在
            var reg = new RegExp('-', 'g');
            beginTime = beginTime.replace(reg, '/');// 正则替换
            beginTime = new Date(parseInt(Date.parse(beginTime), 10));
            return beginTime >= endTime;
        } else {
            return false;
        }

    }, "“到期时间”必须大于当前时间");

    // 输入有效性验证
    $("#formShopTypeSelect,#validateForm,#shopDetailForm").each(function () {
        $(this).validate({
            debug: true,
            ignore: "",
            errorPlacement: function (error, element) {
                error.insertAfter(element);
            }
        });
    });

    // 初始化表格控件
    shopTable = $('#shopTable').DataTable({
        "processing": true,
        "serverSide": true,
        "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
        "dom": '<"bottom"rtflp>',
        "searching": false,
        "pagingType": "full_numbers",
        "deferRender": true,
        "ajax": {
            "url": "/shop/shopList.action",
            "data": function (d) {
                d.quickSearch = encodeURI($('#quickSearch').val());
            }
        },
        "tableTools": {
            // "sSwfPath": "/js/datatables/tabletools/swf/copy_csv_xls_pdf.swf",
            // // 表格导出，需要flash支持
            "sRowSelect": "bootstrap"
        },
        "columns": [{
            "data": "shopName"
        }, {
            "data": "shopType"
        }, 
        /*{
            "data": "shopAccount"
        }, */
        /*{
            "data": "validateStatus"
        }, */
        {
            "data": "status"
        }, {
            "data": "prjName"
        }, /*
         * { "data" : "parentshopname" },
         */{
            "data": "expireTime"
        }, {
            "data": "operation"
        } /*
         * , { "data" : "shopId" }, { "data" : "validate" }, { "data" :
         * "enable" }
         */],
        "columnDefs": [/*
         * { "orderable" : false, "targets" : [ 8 ] }, {
         * "targets" : [ 9 ], "visible" : false, "searchable" :
         * false }, { "targets" : [ 10 ], "visible" : false,
         * "searchable" : false }, { "targets" : [ 11 ],
         * "visible" : false, "searchable" : false }
         */]
        ,"order": [[4, "desc"]]
    });

    // 快速搜索，点击时提交表格刷新内容
    $("#btnQuickSearch").click(function () {
        shopTable.draw();
    });

    // 快速搜索，点击时提交表格刷新内容
    $("#btnQuickSearch").click(function () {
        shopTable.draw();
    });

    // 店铺修改，保存按钮点击事件绑定
    $("#btnShopDetailSave").click(function () {
        updateShop();
    });
    // 选择仓库按钮点击事件绑定
    $("#btnSelectWarehouse").click(function () {
        emptyShopStorPage();
        selectWarehouse();
        // 标题、按钮文字调整
        $("#modal-header-select-warehouse", window.top.document).html("添加仓库");
        $("#btnWarehouseSelectOK", window.top.document).text("添加");
    });

    // 选择默认退货仓库
    $("#btnSelectDefaultReturnWarehouse").click(function () {
        var selectedShopStor = $("#shopWarehouseTable", window.top.document).find("input.icheck:not(.checkall):checked").map(function () {
            return $(this).attr("id");
        }).get().join();

        var optionalStorList = $($("#shopWarehouseTable", window.top.document).DataTable().data()).map(function (index, element) {
            var returnObj = {};
            returnObj.storId = element.storId;
            returnObj.storName = element.storName;
            returnObj.storCode = element.storCode;
            return returnObj;
        }).get();

        if (!selectedShopStor) {
            window.top.window.showModalAlert("请选择仓库进行设置");
            return;
        }

        emptyShopStorPage_defaultReturnStor();
        selectWarehouse_defaultReturnStor(optionalStorList, selectedShopStor);
    });

    // 店铺修改，保存按钮点击事件绑定
    $("#btnShopSwitchSetSave").click(function () {
        updateShopSwitchSet();
    });

    // 编辑对话框关闭事件发生
    $('#modalEdit').on('hide.bs.modal', function () {
        // 父窗体归还本页的编辑对话框
        window.top.window.returnCustomModalDialog();
    });

    // 仓库添加对话框关闭事件发生
    $('#modalWarehouseSelect').on('hide.bs.modal', function () {
        // 父窗体归还本页的编辑对话框
        window.top.window.returnCustomModalDialog();
        window.top.window.borrowCustomModalDialog($("#modalEdit"));
        shopWarehouseTable.draw();
    });

    // 仓库添加退货仓库关闭事件发生
    $('#modalDefaultReturnWarehouseSelect').on('hide.bs.modal', function () {
        // 父窗体归还本页的编辑对话框
        window.top.window.returnCustomModalDialog();
        window.top.window.borrowCustomModalDialog($("#modalEdit"));
        shopWarehouseTable.draw();
    });

    // 确认添加仓库
    $('#btnWarehouseSelectOK').click(function () {
        saveSelectedWarehouse();
    })

    // 点击新建验证店铺
    $('#validateShop').click(function () {
        validateShop();
    });
    // 点击编辑页面的验证店铺
    $('#btnValidation').click(function() {
        validateShop2();
    });

    // 搜索框的回车事件
    $('#quickSearch').keydown(function (e) {
        if (e.keyCode == 13) {
            $("#btnQuickSearch").click();
        }
    });

    // 日期型控件
    $('#divExpireTime').datetimepicker();

    // 确认添加默认退货仓库
    $('#btnDefaultReturnWarehouseSelectOK').click(function () {
        saveSelectedDefaultReturnWarehouse();
    })

    /** ********** 创建店铺向导窗口 ********** */
    function validatePreviousSteps(nextIndex) {
        // 输入有效性验证
        if (nextIndex > 0 && !$("#formShopTypeSelect", wizard).valid()) {
            return false;
        }

        if (nextIndex > 1 && !$("#validateForm", wizard).valid()) {
            $(wizard).bootstrapWizard('show', 1);
            return false;
        }

        // 验证店铺是否有效
        if (nextIndex > 1 && !isValidShop(wizard, 2)) {
            window.top.window.showModalAlert("店铺验证未通过，请重新验证");
            return false;
        }

        // 检测店铺名称+店铺类型是否唯一
        if (nextIndex > 1 && !isShopUnique(wizard, 2)) {
            window.top.window.showModalAlert("店铺名称 + 店铺类型 + 项目名称不唯一");
            return false;
        }

        return true;
    }

    wizard.bootstrapWizard({
        withVisible: false,
        onTabShow: function (tab, navigation, index) {
            if (index == 3) {
                $("#btnShopWizardOK", wizard).removeClass("hidden");
                // $(".button-previous").removeClass("hidden");
                $(".button-next", wizard).addClass("hidden");
            } else {
                $("#btnShopWizardOK", wizard).addClass("hidden");
                // $(".button-previous").removeClass("hidden");
                $(".button-next", wizard).removeClass("hidden");
            }
            var $total = navigation.find('li').length;
            var $current = index + 1;
            var $percent = ($current / $total) * 100;
            $(wizard).find('.bar').css({
                width: $percent + '%'
            });
        },
        'onNext': function (tab, navigation, index) {
            return validatePreviousSteps(index);
        },
        'tabClass': 'bwizard-steps-o',
        'nextSelector': '.button-next',
        'previousSelector': '.button-previous'
    });

    // 初始化项目列表
    $.ajax({
        type: "GET",
        url: "/projectManager/getAllAvailableProjects.action",
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        //async: true,// 异步
        success: function (data) {
            if (data.result == "success") {
                $("#prjId option").remove();
                $("#prjId1 option").remove();
                $("#prjId").append("<option value=''>请选择</option>");
                $("#prjId1").append("<option value=''>请选择</option>");
                $.each(data.data, function (n, value) {
                    $("#prjId").append("<option value='" + value.prjId + "'>" + value.prjName + "</option>");
                    $("#prjId1").append("<option value='" + value.prjId + "'>" + value.prjName + "</option>");
                });
            } else {
                window.top.window.showModalAlert(data.msg);
            }
        },
        error: function (XMLHttpRequest, textStatus) {
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                alert(result.errorObject.errorText);
            }
        }
    });

    // 构建渠道下拉列表
    $.ajax({
        type: "GET",
        url: "/channel/getChannelList.action",
        data: {
            quickSearch: encodeURI(""),
            start: 0,
            length: 2147483647
        },
        // data: function ( d ) {
        // d.quickSearch = encodeURI("");
        // d.start = 0;
        // d.length = 2147483647;
        // },
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        //async: true, // 异步
        success: function (data) {
            if (data.result == "success") {
                $("#channel option").remove();
                $("#channel").append("<option value=''>请选择</option>");
                $.each(data.data, function (n, value) {
                    $('#channel').append("<option value='" + value.channelId + "'>" + value.channelName + "</option>");
                });

                $("#channel1 option").remove();
                $("#channel1").append("<option value=''>请选择</option>");
                $.each(data.data, function (n, value) {
                    $('#channel1').append("<option value='" + value.channelId + "'>" + value.channelName + "</option>");
                });
            } else {
                window.top.window.showModalAlert(data.msg);
            }
        },
        error: function (XMLHttpRequest, textStatus) {
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                alert(result.errorObject.errorText);
            }
        }
    });

    // 加载父店铺列表
    loadParentShops();
    // 店铺创建向导页面，需要分单，就禁止选择父店铺
    $("#needSplitOrder").change(function () {
        if ($("#needSplitOrder", window.top.document).val() == 'y') {
            $("#parentShop", window.top.document).attr({
                "disabled": "disabled"
            });
            $("#parentShop", window.top.document).val("");
        } else {
            $("#parentShop", window.top.document).removeAttr("disabled");
        }
    });

    // 店铺编辑页面，需要分单，就禁止选择父店铺
    $("#needSplitOrder1").change(function () {
        if ($(this).val() == 'y') {
            $(this).parent().parent().parent().find("#parentShop1").attr({
                "disabled": "disabled"
            });
            $(this).parent().parent().parent().find("#parentShop1").val("");
        } else {
            $(this).parent().parent().parent().find("#parentShop1").removeAttr("disabled");
        }
    });

    // 初始化icheck控件
    $('#flat-skin input').iCheck({
        checkboxClass: 'icheckbox_flat-red',
        radioClass: 'iradio_flat-red'
    });
    $('#orderVerifySetting input').iCheck({
        checkboxClass: 'icheckbox_flat-red pull-left',
        radioClass: 'iradio_flat-red pull-left'
    });
    $("#warehouseSelectForm input").iCheck({
        checkboxClass: 'icheckbox_flat-red',
        radioClass: 'iradio_flat-red'
    });

    // 订单审核，收货地址校验1-999个字
    $("#txtRecAddrLength").inputmask("999", {
        greedy: false,
        placeholder: ''
    });
});

/**
 * 加载父店铺下拉列表
 *
 * @returns
 */
function loadParentShops() {
    $.ajax({
        type: "GET",
        url: "/shop/parentShopList.action",
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        //async: true,// 异步
        success: function (data) {
            if (data.result == "success") {
                // 画父店铺select.option
                $("#parentShop option").remove();
                $("#parentShop1 option").remove();
                $("#parentShop").append("<option value=''>请选择</option>");
                $("#parentShop1").append("<option value=''>请选择</option>");
                $.each(data.data, function (n, value) {
                    $("#parentShop").append("<option value='" + value.shopId + "'>" + value.shopName + "</option>");
                    $("#parentShop1").append("<option value='" + value.shopId + "'>" + value.shopName + "</option>");
                });
            } else {
                // window.top.window.showModalAlert(data.msg);
            }
        },
        error: function (XMLHttpRequest, textStatus) {
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                alert(result.errorObject.errorText);
            }
        }
    });
}

// 设置输入框和下拉框不可用的title属性
function setInputSelectTitle() {
    var length = window.top.window.$("input").length;
    for (var i = 0; i < length; i++) {
        if (window.top.window.$("input")[i].disabled || window.top.window.$("input")[i].readOnly) {
            window.top.window.$("input")[i].title = window.top.window.$("input")[i].value;
        }
    }
    var sLength = window.top.window.$("select").length;
    for (var i = 0; i < sLength; i++) {
        if (window.top.window.$("select")[i].disabled) {
            var childLength = window.top.window.$("select")[i].children.length;
            for (var j = 0; j < childLength; j++) {
                if (window.top.window.$("select")[i].children[j].value == window.top.window.$("select")[i].value) {
                    window.top.window.$("select")[i].title = window.top.window.$("select")[i].children[j].text;
                    break;
                }
            }

        }
    }
}

/**
 * 验证店铺是否有效
 *
 * @param index
 * @returns true有效，false无效
 */
function isValidShop(wizard, index) {
    return true;
    var returnResult = false;
    var shopAccount = encodeURI(encodeURI($('#shopAccount', wizard).val()));
    $.ajax({
        type: "GET",
        url: "/shop/isValidShop.action?shopAccount=" + shopAccount,
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        async: false,// 同步
        success: function (data) {
            returnResult = !!data;
        },
        error: function (XMLHttpRequest, textStatus) {
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                window.top.window.showModalAlert(result.errorObject.errorText);
            }
            returnResult = false;
        }
    });
    return returnResult;
}

/**
 * 检测店铺名称+店铺类型唯一性
 *
 * @param index
 * @returns true唯一，false不唯一
 */
function isShopUnique(wizard, index) {
    var returnResult = false;
    var shopName = encodeURI(encodeURI($('#shopName', wizard).val()));
    var shopType = encodeURI(encodeURI($('#shopType', wizard).val()));
    var prjId = encodeURI(encodeURI($('#prjId', wizard).val()));
    $.ajax({
        type: "GET",
        url: "/shop/isShopUnique.action?shopName=" + shopName + "&shopType=" + shopType + "&prjId=" + prjId,
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        async: false,// 同步
        success: function (data) {
            returnResult = !!data;
        },
        error: function (XMLHttpRequest, textStatus) {
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                window.top.window.showModalAlert(result.errorObject.errorText);
            }
            returnResult = false;
        }
    });
    return returnResult;
}

/**
 * 弹出创建店铺向导
 *
 * @returns
 */
function newShopWizard() {
    window.top.window.borrowCustomModalDialog($('#newShopWizard'));
    $("#newShopWizard", window.top.document).modal("show").one("hidden.bs.modal", function () {
        window.top.window.returnCustomModalDialog();
    });

    wizard.bootstrapWizard('show', 0);
    $("#validateForm", window.top.document)[0].reset();
    $("#formShopTypeSelect", window.top.document)[0].reset();
    wizard.find("#formShopTypeSelect").validate().clear();
    wizard.find("#validateForm").validate().clear();
    wizard.find("#formSettings").validate().clear();
}

/**
 * 删除提示
 *
 * @param btnDelete
 * @returns
 */
function operationDelete(btnDelete) {
    opShopId = $(btnDelete).attr("shopid");
    window.top.window.showModalConfirm("确定要删除店铺吗？", doDelete);
}

/**
 * 执行删除店铺操作
 *
 * @returns
 */
function doDelete() {
    if (opShopId == "") {
        return;
    }
    var loading = window.top.window.getIndexBusyOverlay();
    $.ajax({
        type: "POST",
        url: "/shop/deleteShop.action?shopId=" + opShopId,
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        //async: false,// 同步
        beforeSend:function(){
            if(loading) {
            	loading.settext("正在处理中，请稍后...");
            }
        },
        success: function (data) {
        	loading.remove();
            if (data.result == "success") {
                window.top.window.showScoMessage('ok', '删除成功');
            } else {
                window.top.window.showModalAlert(data.msg);
            }
        },
        error: function (XMLHttpRequest, textStatus) {
        	loading.remove();
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                alert(result.errorObject.errorText);
            }
        }
    });
    opShopId = "";
    shopTable.draw();
}

// 确认操作提示
var strOperation = "";

/**
 * 启用、停用操作点击
 *
 * @param btnEnable
 * @returns
 */
function operationEnable(btnEnable) {
    opShopId = $(btnEnable).attr("shopid");
    var content = "";
    if ($(btnEnable).text().indexOf("启用") > 0) {
        content = "是否确认启用该店铺？";
        strOperation = "setEnable";
    } else {
        content = "停用店铺将停止该店铺所有系统作业，是否确认停用？";
        strOperation = "setDisable";
    }
    window.top.window.showModalConfirm(content, doEnable);
}

/**
 * 具体执行启用、停用操作
 *
 * @returns
 */
function doEnable() {
    if (opShopId == "") {
        return;
    }
    var loading = window.top.window.getIndexBusyOverlay();
    $.ajax({
        type: "POST",
        url: "/shop/" + strOperation + ".action?shopId=" + opShopId,
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        //async: false,// 同步
        beforeSend:function(){
            if(loading) {
            	loading.settext("正在处理中，请稍后...");
            }
        },
        success: function (data) {
        	loading.remove();
            if (data.result == "success") {
                window.top.window.showScoMessage('ok', '成功');
            } else {
                window.top.window.showModalAlert(data.msg);
            }
            shopTable.draw();
        },
        error: function (XMLHttpRequest, textStatus) {
        	loading.remove();
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                alert(result.errorObject.errorText);
            }
        }
    });
}

/**
 * 编辑按钮点击
 *
 * @param btnEdit
 * @returns
 */
function operationEdit(btnEdit) {
    $("#shopDetailForm")[0].reset();
    opShopId = $(btnEdit).attr("shopid");

    // 初始化项目列表
    var loading = window.top.window.getIndexBusyOverlay();
    $.ajax({
        type: "GET",
        url: "/shop/shopDetail.action?shopId=" + opShopId,
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        //async: false,// 同步
        beforeSend:function(){
            if(loading) {
            	loading.settext("正在处理中，请稍后...");
            }
        },
        success: function (data) {
        	loading.remove();
            if (data.result == "success") {
                $("#modalEdit").attr("shopid", opShopId);
                if (data.data.prjId != "") {
                    //$("#prjId1").append("<option value='" + data.data.prjId + "'>" + data.data.prjName + "</option>");
                    $("#prjId1").val(data.data.prjId);
                }
                if (data.data.channelId != "") {
                    //$("#channel1").append("<option value='" + data.data.channelId + "'>" + data.data.channelName + "</option>");
                    $("#channel1").val(data.data.channelId);
                }

                var validTab = $("#validinfo-tab");

                $("#shopName1").val(data.data.shopName);
                $("#shopType1").val(data.data.shopType);
                $("#needSplitOrder1").val(data.data.needSplitOrder);
                $("#parentShop1").val(data.data.parentShop);
                $("#expireTime").val(data.data.expireTime);
                $("#remark").val(data.data.remark);

                // 填充验证信息
                $("#apiUrl", validTab).val(data.data.apiUrl);
                $("#appKey2",validTab).val(data.data.appKey);
                $("#appSecret2",validTab).val(data.data.appSecret);
                $("#sessionKey", validTab).val(data.data.sessionKey);
                $("#sessionKeyPrev", validTab).val(data.data.sessionKey);
                $("#refreshToken", validTab).val(data.data.refreshToken);
                $("#dbUrl", validTab).val(data.data.dbUrl);
                $("#dbUsername", validTab).val(data.data.dbUsername);
                $("#dbPassword", validTab).val(data.data.dbPassword);

                // 没有验证的店铺可以修改，验证以后不能修改
                if (data.data.validate == 'n') {
                    $("#prjId1").removeAttr("disabled");
                    $("#shopName1").removeAttr("disabled");
                    $("#shopType1").removeAttr("disabled");
                    $("#needSplitOrder1").removeAttr("disabled");
                    $("#parentShop1").removeAttr("disabled");

                    //没有验证的店铺可以修改验证信息，并执行验证
//                    $("#apiUrl", validTab).removeAttr("disabled");
//                    $("#appKey2",validTab).removeAttr("disabled");
//                    $("#appSecret2",validTab).removeAttr("disabled");
//                    $("#sessionKey", validTab).removeAttr("disabled");
//                    $("#refreshToken", validTab).removeAttr("disabled");
//                    $("#dbUrl", validTab).removeAttr("disabled");
//                    $("#dbUsername", validTab).removeAttr("disabled");
//                    $("#dbPassword", validTab).removeAttr("disabled");
                } else {
                    $("#prjId1").attr({
                        "disabled": "disabled"
                    });
                    $("#shopName1").attr({
                        "disabled": "disabled"
                    });
                    $("#shopType1").attr({
                        "disabled": "disabled"
                    });
                    $("#needSplitOrder1").attr({
                        "disabled": "disabled"
                    });
                    $("#parentShop1").attr({
                        "disabled": "disabled"
                    });

//                    $("#apiUrl", validTab).attr("disabled", "disabled");
//                    $("#appKey2",validTab).attr("disabled","disabled");
//                    $("#appSecret2",validTab).attr("disabled","disabled");
//                    $("#refreshToken", validTab).attr("disabled", "disabled");
//                    $("#dbUrl", validTab).attr("disabled", "disabled");
//                    $("#dbUsername", validTab).attr("disabled", "disabled");
//                    $("#dbPassword", validTab).attr("disabled", "disabled");
                }

                // 加载父店铺列表
                loadParentShops();

                // 显示此店铺下的仓库
                drawShopWarehouseTable();

                // 父窗体借用本页的编辑对话框
                var editDialog = window.top.window.borrowCustomModalDialog($("#modalEdit"));
                editDialog.modal({
                    show: true,
                    backdrop: 'static'
                });

            } else {
                window.top.window.showScoMessage('ok', data.msg);
            }
            // 显示"店铺详情"tab页。
            $("#generalTab > li:nth-child(1)", window.top.document).tab("show");
            $("#warehouse-tab", window.top.document).removeClass("fade active in");
            $("#validinfo-tab", window.top.document).removeClass("fade active in");
            $("#detail-tab", window.top.document).addClass("fade active in");

        },
        error: function (XMLHttpRequest, textStatus) {
        	loading.remove();
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                alert(result.errorObject.errorText);
            }
        }
    });
}

/**
 * 创建任务
 * @param btnInit
 * @returns
 */
function operationInit(btnInit) {
    var shopid = $(btnInit).attr("shopid");
    var loading = window.top.window.getIndexBusyOverlay();
    $.ajax({
        type: "POST",
        url: "/shop/initShop/" + shopid + ".action",
        data: null,
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        beforeSend:function(){
            if(loading) {
            	loading.settext("正在处理中，请稍后...");
            }
        },
        success: function (json) {
        	loading.remove();
            if (json.result == "true") {
                window.top.window.showScoMessage('ok', '创建任务成功');
            } else {
                window.top.window.showModalAlert(json.msg);
            }
        }
    });
}

/**
 * 授权
 * @param btnAuthorization
 * @returns
 */
function operationAuthorization(btnAuthorization) {
    // 如果是淘宝平台，就执行调用
    var trDom = $(btnAuthorization).parents("tr:eq(0)")[0];
    var dataTableRow = shopTable.row(trDom);
    // 如果是唯品会直发，执行下面的逻辑
    var rowData = dataTableRow.data();
    if (rowData.shopType == "唯品会直发" || rowData.shopType == "苏宁") {
        var shopid = $(btnAuthorization).attr("shopid");
        var loading = window.top.window.getIndexBusyOverlay();
        $.ajax({
            type: "GET",
            url: "/authorization/getAuthorizationUrl.action?shopId=" + shopid,
            data: null,
            contentType: "application/json;charset=utf-8",
            dataType: "json",
            beforeSend:function(){
                if(loading) {
                	loading.settext("正在处理中，请稍后...");
                }
            },
            success: function (json) {
            	loading.remove();
                if (json.success == "true") {
                    window.open(json.msg);
                } else {
                    window.top.window.showModalAlert(json.msg);
                }
            }
        });
    } else if (rowData.shopType == "淘宝") {
        var callbackURL = "http://oms.ruixuesoft.com/shop/validated.action?appKey=" + rowData.appKey + "&appSecret="
            + rowData.appSecret
        var url = "https://oauth.taobao.com/authorize?response_type=code&client_id=" + rowData.appKey + "&redirect_uri="
            + encodeURIComponent(callbackURL) + "&state=1212&view=web";
        window.open(url);
    }

}

/**
 * 开关设置按钮点击
 *
 * @param
 * @returns
 */
function operationSwitchSet(btnSwitchSet) {
    // 初始化开关设置页面
    opShopId = $(btnSwitchSet).attr("shopid");
    // 清空checkbox插件
    $('#flat-skin input').iCheck("uncheck");
    $('#orderVerifySetting input').iCheck("uncheck");
    $("#txtRecAddrLength").val("0");
    if (!opShopId) {
        return;
    } else {
        // 初始化项目列表
    	var loading = window.top.window.getIndexBusyOverlay();
        $.ajax({
            type: "GET",
            url: "/shop/shopDetail.action?shopId=" + opShopId,
            contentType: "application/json;charset=utf-8",
            dataType: "json",
            //async: false,// 同步
            beforeSend:function(){
                if(loading) {
                	loading.settext("正在处理中，请稍后...");
                }
            },
            success: function (data) {
            	loading.remove();
                if (data.result == "success") {
                    // 初始化checkbox
                    var shopData = data.data;

                    if ('y' == shopData.isSyncInventory) {
                        $('#chkIsSyncInventory').iCheck('check');
                    }
                    if ('y' == shopData.isAutoPlatformDelivery) {
                        $('#chkIsAutoPlatformDelivery').iCheck('check');
                    }
                    if ('y' == shopData.isAutoAuthen) {
                        $('#chkIsAutoAuthen').iCheck('check');
                    }
                    if ('y' == shopData.isAutoMergeOrder) {
                        $('#chkIsAutoMergeOrder').iCheck('check');
                    }
                    if ('y' == shopData.isAutoGenerateReturn) {
                        $('#chkIsAutoGenerateReturn').iCheck('check');
                    }

                    // 订单审核设置
                    if ('y' == shopData.hasCustRemark) {
                        $('#hasCustRemark').iCheck('check');
                    }
                    if ('y' == shopData.hasSalesRemark) {
                        $('#hasSalesRemark').iCheck('check');
                    }
                    if ('y' == shopData.isCheckCanallotqty) {
                        $('#isCheckCanallotqty').iCheck('check');
                    }
                    if ('0' != shopData.orderConsAddrLen) {
                        $('#orderConsAddrLen').iCheck('check');
                        $("#txtRecAddrLength").val(shopData.orderConsAddrLen);
                    } // 订单审核设置

                    var shopName = shopData.shopName || "店铺";

                    $("#modal-header-primary-label", $("#modalSwitchSet")).text("店铺开关设置-" + shopName);

                    var switchSetDialog = window.top.window.borrowCustomModalDialog($("#modalSwitchSet").attr("shopid", opShopId));
                    switchSetDialog.on('hide.bs.modal', function () {
                        // 父窗体归还本页的编辑对话框
                        window.top.window.returnCustomModalDialog();
                    });
                    switchSetDialog.modal({
                        show: true,
                        backdrop: 'static'
                    });
                } else {
                    window.top.window.showScoMessage('ok', data.msg);
                }
            },
            error: function (XMLHttpRequest, textStatus) {
            	loading.remove();
                if (XMLHttpRequest.status == 500) {
                    var result = eval("(" + XMLHttpRequest.responseText + ")");
                    alert(result.errorObject.errorText);
                }
            }
        });
    }
}

/**
 * 更新店铺开关设置
 *
 * @param
 * @returns
 */
function updateShopSwitchSet() {
    // 父窗体归还本页的编辑对话框。
    // 此步骤必须做，否则取不到设置内容
    window.top.window.returnCustomModalDialog();
    opShopId = $("#modalSwitchSet").attr("shopid");
    // 获取icheck对象状态
    var shopId = opShopId;
    var chkIsSyncInventory = $("#chkIsSyncInventory").attr("checked");
    var chkIsAutoAuthen = $("#chkIsAutoAuthen").attr("checked");
    var chkIsAutoPlatformDelivery = $("#chkIsAutoPlatformDelivery").attr("checked");
    var chkIsAutoMergeOrder = $("#chkIsAutoMergeOrder").attr("checked");
    var chkIsAutoGenerateReturn = $("#chkIsAutoGenerateReturn").attr("checked");
    var hasCustRemark = $("#hasCustRemark").attr("checked");
    var hasSalesRemark = $("#hasSalesRemark").attr("checked");
    var isCheckCanallotqty = $("#isCheckCanallotqty").attr("checked");
    // 订单审核，收货地址长度
    var addrLength = 0;
    if ($("#orderConsAddrLen").attr("checked") == "checked") {
        addrLength = $("#txtRecAddrLength").val() ? $("#txtRecAddrLength").val() : 0;
    }
    var data = {
        "shopId": shopId,
        "isSyncInventory": "checked" == chkIsSyncInventory ? "y" : "n",
        "isAutoAuthen": "checked" == chkIsAutoAuthen ? "y" : "n",
        "isAutoPlatformDelivery": "checked" == chkIsAutoPlatformDelivery ? "y" : "n",
        "isAutoMergeOrder": "checked" == chkIsAutoMergeOrder ? "y" : "n",
        "isAutoGenerateReturn": "checked" == chkIsAutoGenerateReturn ? "y" : "n",
        "hasCustRemark": "checked" == hasCustRemark ? "y" : "n",
        "hasSalesRemark": "checked" == hasSalesRemark ? "y" : "n",
        "isCheckCanallotqty": "checked" == isCheckCanallotqty ? "y" : "n",
        "orderConsAddrLen": addrLength
    }
    
    var loading = window.top.window.getIndexBusyOverlay();
    $.ajax({
        type: "POST",
        url: "/shop/updateShopSwitchSet.action",
        data: JSON.stringify(data),
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        //async: false,// 同步
        beforeSend:function(){
            if(loading) {
            	loading.settext("正在处理中，请稍后...");
            }
        },
        success: function (data) {
        	loading.remove();
            if (data.result == "success") {
                $('#modalSwitchSet').modal('hide');
                window.top.window.showScoMessage('ok', '开关设置保存成功！');
            } else {
                window.top.window.showModalAlert(data.msg);
            }
        },
        error: function (XMLHttpRequest, textStatus) {
        	loading.remove();
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                window.top.window.showModalAlert(result.errorObject.errorText);
            }
        }
    });
    shopTable.draw();
}

/**
 * 保存新店铺
 *
 * @returns
 */
window.top.window.shopWizardFinish = function () {
    var prjId = $('#prjId', wizard).val();
    var prjName = $('#prjId', wizard).find("option:selected").text();
    var channelId = $('#channel', wizard).val();
    var channelName = $('#channel', wizard).find("option:selected").text();
    var shopName = $('#shopName', wizard).val();
    var shopAccount = $('#shopAccount', wizard).val();
    var shopPassword = $('#shopPassword', wizard).val();
    var appKey = $('#appKey', wizard).val();
    var appSecret = $('#appSecret', wizard).val();
    var shopType = $('#shopType', wizard).val();
    var enable = $('#enable', wizard).val();
    var needSplitOrder = $("#needSplitOrder", wizard).val();
    var parentShop = $("#parentShop", wizard).val();
    var expireTime = $('#expireTime1', wizard).val();
    shopAccount="";
    var data = {
        "prjId": prjId,
        "prjName": prjName,
        "channelId": channelId,
        "channelName": channelName,
        "shopType": shopType,
        "shopName": shopName,
        "shopAccount": shopAccount,
        "shopPassword": shopPassword,
        "appKey": appKey,
        "appSecret": appSecret,
        "expireTime": expireTime,
        "enable": enable,
        "needSplitOrder": needSplitOrder,
        "parentShop": parentShop
    };
    var loading = window.top.window.getIndexBusyOverlay();
    $.ajax({
        type: "POST",
        url: "/shop/addShop.action",
        data: JSON.stringify(data),
        contentType: "application/json;charset=utf-8",
        dataType: "json",
//        async: false,// 同步
        beforeSend:function(){
            if(loading) {
            	loading.settext("正在处理中，请稍后...");
            }
        },
        success: function (data) {
        	loading.remove();
            if (data.result == "success") {
                $('#newShopWizard', window.top.document).modal('hide');
                window.top.window.showScoMessage('ok', '创建店铺成功');
            } else {
                window.top.window.showModalAlert(data.msg);
            }
            shopTable.draw();
        },
        error: function (XMLHttpRequest, textStatus) {
        	loading.remove();
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                alert(result.errorObject.errorText);
            }
        }
    });
//    shopTable.draw();
}

/**
 * 保存店铺
 *
 * @returns
 */
function updateShop() {
    // 父窗体归还本页的编辑对话框
    window.top.window.returnCustomModalDialog();

    var shopId = $("#modalEdit").attr("shopid");
    if (shopId == undefined || shopId == null || shopId == "") {
        window.top.window.borrowCustomModalDialog($("#modalEdit"));
        window.top.window.showModalAlert("未指定店铺");
        return false;
    }

    // 输入有效性验证
    if (!$("#shopDetailForm").valid()) {
        // 父窗体借用本页的编辑对话框
        window.top.window.borrowCustomModalDialog($("#modalEdit"));
        // 显示"店铺详情"tab页。
        $("#generalTab > li:nth-child(1)", window.top.document).tab("show");
        $("#warehouse-tab", window.top.document).removeClass("fade active in");
        $("#validinfo-tab", window.top.document).removeClass("fade active in");
        $("#detail-tab", window.top.document).addClass("fade active in");
        return false;
    }

    var prjId = $("#prjId1").val();
    var shopName = $("#shopName1").val();
    var shopType = $("#shopType1").val();
    var needSplitOrder = $("#needSplitOrder1").val();
    var parentShop = $("#parentShop1").val();
    var channelId = $('#channel1').val();
    var channelName = $('#channel1').find("option:selected").text();
    var expireTime = $("#expireTime").val();
    var remark = $("#remark").val();

    var validTab = $("#validinfo-tab");
    //var apiUrl = $("#apiUrl", validTab).val();
    var appKey = $("#appKey2",validTab).val();
    //var appSecret = $("#appSecret2",validTab).val();
    //var sessionKey = $("#sessionKey", validTab).val();
    //var sessionKeyPrev = $("#sessionKeyPrev", validTab).val();
    //var refreshToken = $("#refreshToken", validTab).val();
    //var dbUrl = $("#dbUrl", validTab).val();
    //var dbUsername = $("#dbUsername", validTab).val();
    //var dbPassword = $("#dbPassword", validTab).val();
    var validate = "n";

    // 根据apiUrl组件是否disabled知道店铺验证是否已经通过
    /*if ($("#apiUrl", validTab).is(":disabled")) {
        if (sessionKey === sessionKeyPrev) {
            validate = "y"
        }
    }*/

    var data = {
        "shopId": shopId,
        "prjId": prjId,
        "shopType": shopType,
        "needSplitOrder": needSplitOrder,
        "parentShop": parentShop,
        "shopName": shopName,
        "channelId": channelId,
        "channelName": channelName,
        "expireTime": expireTime,
        "remark": remark

        // 添加校验信息
        //, "apiUrl": apiUrl
        , "appKey": appKey
        //, "appSecret": appSecret
        //, "sessionKey": sessionKey
        //, "refreshToken": refreshToken
        //, "dbUrl": dbUrl
        //, "dbUsername": dbUsername
        //, "dbPassword": dbPassword
        , "validate": validate
    };

    var loading = window.top.window.getIndexBusyOverlay();
    $.ajax({
        type: "POST",
        url: "/shop/updateShop.action",
        data: JSON.stringify(data),
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        //async: false, // 同步
        beforeSend:function(){
            if(loading) {
            	loading.settext("正在处理中，请稍后...");
            }
        },
        success: function (data) {
        	loading.remove();
            if (data.result == "success") {
                $('#modalEdit').modal('hide');
                window.top.window.showScoMessage('ok', '修改成功');
            } else {
                window.top.window.showModalAlert(data.msg);
            }
        },
        error: function (XMLHttpRequest, textStatus) {
        	loading.remove();
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                alert(result.errorObject.errorText);
            }
        }
    });
    shopTable.draw();
}

/**
 * 验证店铺
 */
function validateShop() {
    var callbackURL = "http://oms.ruixuesoft.com/shop/validated.action?appKey=" + $("#appKey", wizard).val() + "&appSecret="
        + $("#appSecret", wizard).val()
    var url = "https://oauth.taobao.com/authorize?response_type=code&client_id=" + $("#appKey", wizard).val() + "&redirect_uri="
        + encodeURIComponent(callbackURL) + "&state=1212&view=web";
    window.open(url);
}

function validateShop2() {
    var shopId =  $("#modalEdit", window.top.document).attr("shopId");
    var shopName = $("#shopName1", window.top.document).val();
    var shopType = $("#shopType1", window.top.document).val();
    var apiUrl = $("#apiUrl", window.top.document).val();
    var appKey = $("#appKey2", window.top.document).val();
    var appSecret = $("#appSecret2", window.top.document).val();
    var sessionKey = $("#sessionKey", window.top.document).val();
    var shop = {"shopId":shopId, "shopName":shopName, "shopType":shopType, "appKey":appKey, "appSecret":appSecret, 
            "apiUrl":apiUrl, "sessionKey":sessionKey};
    var validator = new ShopValidator(shop);
    validator.validate();
}
/**
 * 弹出添加仓库页面
 */
function selectWarehouse() {
    // 获取主框架右上角，选择的当前项目
    var currProjectId = $("#projectSwitch", window.top.document).val();
    if (currProjectId == null || currProjectId == "") {
        window.top.window.showModalAlert("未选择项目");
        return false;
    }

    var projectStorData = window.top.window.projectStorData;

    // 父窗体归还本页的编辑对话框。
    window.top.window.returnCustomModalDialog();

    // 清空仓库select框
    $("#storSelect").empty();

    // 把仓库放到select框里供选择
    $("#storSelect").append("<option value=''>请选择</option>");
    $.each(projectStorData, function (n, value) {
        $("#storSelect").append("<option value='" + value.storId + "' code='" + value.storCode + "'>" + value.storName + "(" + value.storCode + ")" + "</option>");
    });
    // 在主框架下打开仓库选择modal框
    var selectDialog = window.top.window.borrowCustomModalDialog($("#modalWarehouseSelect"));
    selectDialog.modal({
        show: true,
        backdrop: 'static'
    });
}

/**
 * 弹出添加退货仓库页面
 */
function selectWarehouse_defaultReturnStor(optionalStorList, selectedShopStorId) {
    // 获取主框架右上角，选择的当前项目
    var currProjectId = $("#projectSwitch", window.top.document).val();
    if (currProjectId == null || currProjectId == "") {
        window.top.window.showModalAlert("未选择项目");
        return false;
    }

    var projectStorData = window.top.window.projectStorData;
    // 父窗体归还本页的编辑对话框。
    window.top.window.returnCustomModalDialog();

    // 清空仓库select框
    $("#returnStorSelect").empty();

    // 把仓库放到select框里供选择
    $("#returnStorSelect").append("<option value=''>空</option>");
    $.each(optionalStorList, function (n, value) {
        $("#returnStorSelect").append("<option value='" + value.storId + "' code='" + value.storCode + "'>" + value.storName + "</option>");
    });

    // 把选中的店铺仓库设置到shopStorIds中
    $("#shopStorIds").val(selectedShopStorId);

    // 在主框架下打开默认退货仓库选择modal框
    var selectDialog = window.top.window.borrowCustomModalDialog($("#modalDefaultReturnWarehouseSelect"));
    selectDialog.modal({
        show: true,
        backdrop: 'static'
    });
};

// 弹出成展示后加title
$('#modalEdit').on('shown.bs.modal', function () {
    setInputSelectTitle();
});

var setProjectStorIdData = function () {
    var currProjectId = $("#projectSwitch", window.top.document).val();

    $.ajax({
        type: "GET",
        url: "/stor/storageByProjectId.action?projectId=" + currProjectId,
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        async: false,// 同步
        success: function (data) {
            if (data.result == "success") {
                window.top.window.projectStorData = data.data;
            } else {
                window.top.window.showModalAlert(data.msg);
            }
        },
        error: function (XMLHttpRequest, textStatus) {
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                window.top.window.showModalAlert(result.errorObject.errorText);
            }
        }
    });
}

/**
 * 保存用户选择的店铺仓库
 */
function saveSelectedDefaultReturnWarehouse() {
    var data = {
        "shopStorIds": $("#shopStorIds", window.top.window.document).val(),
        "storId": $("#returnStorSelect", window.top.window.document).val()
    };
    $.ajax({
        type: "GET",
        url: "/shop/saveDefaultReturnWarehouse.action",
        data: data,
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        async: false, // 同步
        success: function (data) {
            if (data.result == "success") {
                $('#modalDefaultReturnWarehouseSelect', window.top.window.document).modal('hide');
                window.top.window.showScoMessage('ok', data.msg);
            } else {
                window.top.window.showModalAlert(data.msg);
            }
        },
        error: function (XMLHttpRequest, textStatus) {
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                alert(result.errorObject.errorText);
            }
        }
    });
    drawShopWarehouseTable();
}

/**
 * 保存用户选择的店铺仓库
 */
function saveSelectedWarehouseConfirm(shopStorId, shopId, shopName, storId, storCode, storName, isDefault, isSyncStock, remark) {
    var data = {
        "shopStorId": shopStorId,
        "shopId": shopId,
        "shopName": shopName,
        "storId": storId,
        "storCode": storCode,
        "storName": storName,
        "isDefault": isDefault,
        "isSyncStock": isSyncStock,
        "remark": remark
    };

    $.ajax({
        type: "POST",
        url: "/shop/saveSelectedWarehouse.action",
        data: JSON.stringify(data),
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        async: false, // 同步
        success: function (data) {
            if (data.result == "success") {
                $('#modalWarehouseSelect', window.top.document).modal('hide');
                window.top.window.showScoMessage('ok', data.msg);
            } else {
                window.top.window.showModalAlert(data.msg);
            }
        },
        error: function (XMLHttpRequest, textStatus) {
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                alert(result.errorObject.errorText);
            }
        }
    });
    drawShopWarehouseTable();
}

function saveSelectedWarehouse() {
    // 验证输入有效性，成功后保存
    var shopId = $("#modalEdit").attr("shopid");
    var shopName = $("#shopName1").val();
    var storId = $("#storSelect option:selected", window.top.document).val();
    var storCode = $("#storSelect option:selected", window.top.document).attr("code");
    var storName = $("#storSelect option:selected", window.top.document).text();
    var isDefault = $("#isDefault", window.top.document).prop('checked');
    var isSyncStock = $("#isSyncStock", window.top.document).prop('checked');
    var remark = $("#warehouseRemark", window.top.document).val();
    var shopStorId = $("#shopStorId", window.top.document).val();

    // 输入有效性验证
    if (!storId) {
        window.top.window.showModalAlert("请选择仓库");
        return false;
    }
    var lock = false;
    if (storChooseData.isDefault != "y") {
        if (isDefault) {
            for (var i = 0; i < $("#shopWarehouseTable tbody tr").length; i++) {
                var defaultType = $("#shopWarehouseTable tbody tr:eq(" + i + ") td:eq(0)").text()
                if (defaultType == "是") {
                    var lock = true;
                    break;
                }
            }
        }
    }

    if (lock) {
        window.top.window.showModalConfirm("该店铺已设置默认仓库，是否更新默认仓库？", function () {
            saveSelectedWarehouseConfirm(shopStorId, shopId, shopName, storId, storCode, storName, isDefault, isSyncStock, remark);
        });
    } else {
        saveSelectedWarehouseConfirm(shopStorId, shopId, shopName, storId, storCode, storName, isDefault, isSyncStock, remark);
    }

}

/**
 * 创建店铺仓库列表或者刷新列表。
 */
function drawShopWarehouseTable() {
    setProjectStorIdData();
    if (shopWarehouseTable == null) {
        // 初始化店铺仓库表格控件
        shopWarehouseTable = $('#shopWarehouseTable').DataTable({
            "bPaginate": false,
            "processing": true,
            "serverSide": true,
            "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
            "dom": '<"bottom"rtflp>',
            "searching": false,
            "deferRender": true,
            "ajax": {
                "url": "/shop/getShopWarehouseList.action",
                "data": function (d) {
                    d.shopId = encodeURI(opShopId);
                }
            },
            "drawCallback": function (settings) {
                // 给表格上的按钮绑定点击事件（先移除按钮事件，再添加按钮事件）
                $("#shopWarehouseTable .btnEditShopStor", window.top.document).unbind();
                $("#shopWarehouseTable .btnDeleteShopStor", window.top.document).unbind();
                $("#shopWarehouseTable .btnEditShopStor", window.top.document).on("click", operationEditShopStor);
                $("#shopWarehouseTable .btnDeleteShopStor", window.top.document).on("click", operationDeleteShopStor);
                // 重新初始化表格上icheck风格的checkbox控件
                $("#shopWarehouseTable input[type='checkbox']", window.top.document).iCheck({
                    checkboxClass: 'icheckbox_flat-red',
                    radioClass: 'iradio_flat-red'
                });
                $("#shopWarehouseTable input[type='checkbox']:not(.icheck)", window.top.document).on('ifChecked', function (event) {
                    changeShopStorSyncStatus(0, event.currentTarget.attributes.shopstorid.value);
                });
                $("#shopWarehouseTable input[type='checkbox']:not(.icheck)", window.top.document).on('ifUnchecked', function (event) {
                    changeShopStorSyncStatus(1, event.currentTarget.attributes.shopstorid.value);
                });
                // 设置title
                // 全选
                var tableObj = $("#shopWarehouseTable", window.top.document);
                $("#checkall", tableObj).on("ifChanged", function () {
                    if ($(this).attr("checked")) {
                        $("input.icheck", tableObj).iCheck("check");
                    } else {
                        $("input.icheck", tableObj).iCheck("uncheck");
                    }
                });
                setTitle();
            },
            "tableTools": {
                "sRowSelect": "bootstrap"
            },
            "columns": [{
                "data": "chkbox",
                "defaultContent": ""
            }, {
                "data": "isDefault",
                "render": function (data, type, row, meta) {
                    if (row.isDefault == "y") {
                        return "是";
                    } else {
                        return "否";
                    }
                }
            }, {
                "data": "storName",
            }, {
                "data": "isSyncStock",
                "render": function (data, type, row, meta) {
                    if (row.isSyncStock == 'y') {
                        return "<input type='checkbox' checked='checked' shopStorId='" + row.shopStorId + "'/>";
                    } else {
                        return "<input type='checkbox' shopStorId='" + row.shopStorId + "'/>";
                    }
                }
            }, {
                "data": "returnStor",
                "defaultContent": "",
                "render": function (data, type, row, meta) {
                    for (var i = 0, len = window.top.window.projectStorData.length; i < len; i++) {
                        var storData = window.top.window.projectStorData[i];
                        if (storData.storId == row.returnStorId) {
                            return storData.storName;
                        }
                    }
                }
            }, {
                "data": "remark",
            }, {
                "data": "operation"
            }, {
                "data": "shopStorId"
            }],
            "columnDefs": [{
                "className": "truncate-text",
                "targets": [1]
            }, {
                "className": "truncate-text",
                "targets": [2]
            }, {
                "className": "truncate-text",
                "targets": [3]
            }, {
                "className": "truncate-text",
                "targets": [5]
            }, {
                "orderable": false,
                "targets": [0, 1, 2, 3, 4, 5, 6]
            }, {
                "targets": [7],
                "visible": false,
                "searchable": false
            }]
        }).on('draw.dt', function () {
            //解决因滚动条导致的列对不齐问题
            $("#shopWarehouseTable", window.top.document).find("th.sorting_asc").removeClass("sorting_asc");

            // 重画表格，解决表头与表内容，显示scroll的时候，不对齐的问题。
            $('#shopWarehouseTable', window.top.document).on('shown.bs.modal', function () {
                shopWarehouseTable.draw();
            });

            $('#shopWarehouseTable', window.top.document).find(".icheck").iCheck("unchecked");
        });;
    } else {
        shopWarehouseTable.draw();
    }
}

/**
 * 设置备注的title属性
 */
function setTitle() {
    // 文字过长截断显示悬浮框
    var tem = window.top.window.$("#shopWarehouseTable tbody .truncate-text");
    var length = tem.length;
    for (var i = 0; i < length; i++) {
        tem[i].title = tem[i].innerText;
    }
}

/**
 * 店铺仓库列表上的删除功能
 *
 * @returns
 */
function operationDeleteShopStor(target) {
    var row = shopWarehouseTable.row($(target.srcElement).parents("tr"));
    var rowData = row.data();
    var shopStorId = rowData["shopStorId"];
    window.top.window.showModalConfirm("相关退货仓库将同时清除，是否继续删除？", function () {
        // 删除店铺仓库
        $.ajax({
            type: "GET",
            url: "/shop/deleteShopWarehouse.action?shopStorId=" + shopStorId,
            contentType: "application/json;charset=utf-8",
            dataType: "json",
            async: false, // 同步，删除后再刷新表格
            success: function (data) {
                if (data.result == "success") {
                    drawShopWarehouseTable();
                } else {
                    window.top.window.showModalAlert(data.msg);
                }
            },
            error: function (XMLHttpRequest, textStatus) {
                window.top.window.borrowCustomModalDialog($("#modalEdit"));
                if (XMLHttpRequest.status == 500) {
                    var result = eval("(" + XMLHttpRequest.responseText + ")");
                    alert(result.errorObject.errorText);
                }
            }
        });
    });
}

/**
 * 店铺仓库列表上的编辑功能
 *
 * @returns
 */
function operationEditShopStor(target) {
    var row = shopWarehouseTable.row($(target.srcElement).parents("tr"));
    var rowData = row.data();
    storChooseData = rowData;
    // 弹出页面
    selectWarehouse();

    // 店铺仓库页面控件赋值
    $("#storSelect", window.top.document).find("option[value='" + rowData["storId"] + "']").attr("selected", true);
    if (rowData["isDefault"] == 'y') {
        $("#isDefault", window.top.document).iCheck('check');
    } else {
        $("#isDefault", window.top.document).iCheck('uncheck');
    }
    if (rowData["isSyncStock"] == 'y') {
        $("#isSyncStock", window.top.document).iCheck('check');
    } else {
        $("#isSyncStock", window.top.document).iCheck('uncheck');
    }
    $("#warehouseRemark", window.top.document).val(rowData["remark"]);
    $("#shopStorId", window.top.document).val(rowData["shopStorId"]);

    // 标题、按钮文字调整
    $("#modal-header-select-warehouse", window.top.document).html("修改仓库");
    $("#btnWarehouseSelectOK", window.top.document).text("保存");
}

/**
 * 重置添加仓库页面上的内容
 *
 * @returns
 */
function emptyShopStorPage() {
    $("#storSelect").val("");
    $('#isDefault').iCheck("uncheck");
    $('#isSyncStock').iCheck("uncheck");
    $("#warehouseRemark").val('')
    $("#shopStorId").val("");
}

/**
 * 重置添加默认退货仓库页面上的内容
 */
function emptyShopStorPage_defaultReturnStor() {
    $("#returnStorSelect", $("#defaultReturnWarehouseSelectForm")).val("");
    $("#shopStorIds", $("#defaultReturnWarehouseSelectForm")).val("");
}

/**
 * 店铺仓库列表上，点击checkbox，改变店铺仓库的“同步状态”
 *
 * @param operationFlag
 *            0:checked, 1:unchecked
 * @returns
 */
function changeShopStorSyncStatus(operationFlag, shopStorId) {
    // 删除店铺仓库
    $.ajax({
        type: "GET",
        url: "/shop/changeShopStorSyncStatus.action?shopStorId=" + shopStorId + "&operation=" + operationFlag,
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        async: false, // 同步，删除后再刷新表格
        success: function (data) {
            if (data.result == "success") {
                // 不用刷新了，失败再刷新 drawShopWarehouseTable();
            } else {
                drawShopWarehouseTable();
            }
        },
        error: function (XMLHttpRequest, textStatus) {
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                alert(result.errorObject.errorText);
            }
        }
    });
}
